<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ICamera</title>
  </head>
  <body>
    <video id="video" autoplay="autoplay"></video>
  </body>
  <script>
    // 获得video摄像头区域
    var video = document.getElementById("video");
    var videoStream = null;
    var imageData = null;
    // 页面加载完成自动执行
    window.onload = () => {
      // 获取摄像头视频
      this.getMedia();
    };
    // 双击停止视频并且关闭摄像头
    video.ondblclick = () => {
      window.dialogAPI.quitPhoto("退出拍照");
      this.stopMedia();
      window.opener.postMessage("close-vedio-window");
    };
    // 右键拍照保存
    video.oncontextmenu = () => {
      this.getImgFromVedio();
      // console.log(this.imageData);
      window.dialogAPI.savePicture(this.imageData);
    };
    // 结束获取视频流数据
    function stopMedia() {
      this.videoStream.getTracks()[0].stop();
      this.videoStream.getTracks()[1].stop();
    }
    // 获得视频流数据
    function getMedia() {
      var constraints = {
        video: { width: 200, height: 300 },
        audio: true,
      };
      //   H5新媒体接口 navigator.mediaDevices.getUserMedia()
      var promise = navigator.mediaDevices.getUserMedia(constraints);
      promise
        .then(function (MediaStream) {
          video.srcObject = MediaStream;
          video.play();
          this.videoStream = MediaStream;
          this.stop = false;
        })
        .catch(function (PermissionDeniedError) {
          console.log(PermissionDeniedError);
        });
    }
    // 拍照功能
    function getImgFromVedio() {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      // 将图片数据保存
      this.imageData = canvas.toDataURL("image/png");
      // console.log(canvas.toDataURL("image/png"));
    }
  </script>
</html>

<style>
  #video {
    /* 自适应大小 */
    height: 100%;
    width: 100%;
    display: block;
    /* 设置圆形 */
    border-radius: 2%;
    /* 镜像反转 */
    transform: rotateY(180deg);
    /* 可拖拽 */
    -webkit-app-region: drag;
  }
</style>
